/*
 * @Author: duchengdong
 * @Date: 2021-10-12 16:04:26
 * @LastEditors: duchengdong
 * @LastEditTime: 2021-12-28 21:13:24
 * @Description: 可以删除
 */
import {createSlice, PayloadAction} from '@reduxjs/toolkit'
import {RootState} from './index'
import {BookState} from '../types'
import {uuid} from '../utils/utils'

type initialStateType = {
	bookList: BookState[]
}

const bookList: BookState[] = [
	{
		id: uuid(),
		title: '1984',
		author: 'George Orwell',
	},
	{
		id: uuid(),
		title: "Harry Potter and the Philosopher's Stone",
		author: 'J. K. Rowling',
	},
	{
		id: uuid(),
		title: 'The Lord of the Rings',
		author: 'J.R.R Tolkien',
	},
]

const initialState: initialStateType = {
	bookList,
}

export const bookSlice = createSlice({
	name: 'book',
	initialState,
	reducers: {
		addNewBook: (state, action: PayloadAction<BookState>) => {
			state.bookList.push(action.payload)
		},
		updateBook: (state, action: PayloadAction<BookState>) => {
			const {
				payload: {title, id, author},
			} = action

			state.bookList = state.bookList.map(book => (book.id === id ? {...book, author, title} : book))
		},
		deleteBook: (state, action: PayloadAction<{id: string}>) => {
			state.bookList = state.bookList.filter(book => book.id !== action.payload.id)
		},
	},
})

export const {addNewBook, updateBook, deleteBook} = bookSlice.actions

export const selectBookList = (state: RootState) => state.book.bookList

export default bookSlice.reducer
